<template>
	<view :class="themeName">
		<!-- <view class="title">锤乐拍</view> -->
		<view class="p-30 flex row-center">
			<image class="tops" src="/others/static/logo.png" mode=""></image>
			<view class="operate m-l-35">
				<u-count-down ref="uCountDown" :timestamp="beginTime*60" :autoplay="false" @end="finish" :show-days="false" :font-size="40" />
				<view class="m-t-20 line-1" @click="newconnect">{{stuName}}</view>
			</view>
		</view>
		<view class="boxes">
			<view class="flex row-between m-t-40">
				<view @click="gosend('cmd{01}',1)">启动</view>
				<view @click="gosend('cmd{02}')">暂停</view>
			</view>
			<view class="flex row-between m-t-40">
				<view @click="gosend('cmd{05}')">减轻</view>
				<view @click="gosend('cmd{06}')">加重</view>
			</view>
			<view class="flex row-between m-t-40">
				<view @click="gosend('cmd{03}')">前进</view>
				<view @click="gosend('cmd{04}')">后退</view>
			</view>
			<view class="flex row-between m-t-40">
				<view @click="gosend('cmd{07}')">开频</view>
				<view @click="gosend('cmd{08}')">关频</view>
			</view>
			<view class="flex row-between m-t-40">
				<view @click="gosend('cmd{09}')">播放</view>
				<view @click="gosend('cmd{10}')">关闭</view>
			</view>
		</view>
		<!-- <view class="base" @click="aaa">aaa</view> -->
		<button class="base"  
		@touchstart="handleTouchStart"
		@touchend="handleTouchEnd"
		>长按语音控制</button>
		<loading-view v-show="loading"></loading-view>
	</view>
</template>

<script>
import { startFw,orderInfo } from '@/api/others.js';
import { nextTick } from 'process';
import { audioFile } from '@/utils/tools';
// ArrayBuffer转16进度字符串示例
function ab2hex(buffer) {
	var hexArr = Array.prototype.map.call(new Uint8Array(buffer), function (bit) {
		return ('00' + bit.toString(16)).slice(-2) + ' ';
	});
	return hexArr.join('').toUpperCase();
}
function ab2Str(arrayBuffer) {
	let unit8Arr = new Uint8Array(arrayBuffer);
	let encodedString = String.fromCharCode.apply(null, unit8Arr);
	return encodedString;
}
function stringToBytes(str) {
	var ch,
		st,
		re = [];
	for (var i = 0; i < str.length; i++) {
		ch = str.charCodeAt(i); // get char
		st = []; // set up "stack"
		do {
			st.push(ch & 0xff); // push byte to stack
			ch = ch >> 8; // shift value down by 1 byte
		} while (ch);
		// add stack contents to result
		// done because chars have "wrong" endianness
		re = re.concat(st.reverse());
	}
	// return an array of bytes
	return re;
}
export default {
	data() {
		return {
			recorderManager: {},//录音组件
			id:'',
			type:'',//1支付后启动服务    2 启动后的订单重新启动服务   3店长直控
			status:1,//1首次连接要开始蓝牙定时器 ,并启动倒计时   2 当前页面重新连接，只连接蓝牙不做其他操作
			time:0,
			beginTime:0,//开始倒计时
			systemname: '',
			loading: false,
			jqrdevicename:'',//蓝牙名称
			deviceId: '', //蓝牙设备deviceId
			serviceId: '0000FFE0-0000-1000-8000-00805F9B34FB', //蓝牙设备serviceId
			characteristicId: '0000FFE2-0000-1000-8000-00805F9B34FB', //蓝牙设备characteristicId
			connected: false, //判断是否启动蓝牙
			readyRec: false, //是否成功链接
			stuName:'重新连接',//当前状态
			// devices: []
		};
	},
	onLoad(options) {
		let that = this;
		that.recorderManager = uni.getRecorderManager();
		that.id = options.id;
		that.type = options.type;
		that.jqrdevicename = uni.getStorageSync('jqrdevicename');
		if(options.type==1){//支付后启动订单服务
			that.time = options.time;
			that.$nextTick(() => {
				that.getinit();
			});
		}else if(options.type==2){//启动后的订单继续操控
			orderInfo({id:options.id}).then(res => {
				that.time = res.time;
				that.$nextTick(() => {
					that.getinit();
				});
			});
		}else if(options.type==3){//店长只控
			that.time = options.time;
			that.$nextTick(() => {
				that.getinit();
			});
		}
		// // uni.setStorageSync('jqrdevicename', 'daocheng');
		// console.log('======>操控机器人的蓝牙名称', uni.getStorageSync('jqrdevicename'));
		// if (uni.getStorageSync('jqrdevicename')) {
		// 	that.jqrdevicename = uni.getStorageSync('jqrdevicename');
		// 	that.$nextTick(() => {
		// 		that.getinit();
		// 	});
		// } else {
		// 	uni.showModal({
		// 		content: '未检测到蓝牙设备',
		// 		showCancel: false,
		// 		confirmText: '请联系工作人员查询'
		// 	});
		// }
	},
	created() {
		this.systemname = uni.getSystemInfoSync().osName;
	},
	methods: {
		// 开始录制语音
		handleTouchStart(e){
			if (!this.connected){
				this.$toast({
					title: '请先连接蓝牙设备...'
				})
				return;
			}
			this.recorderManager.start();
		},
		
		// 录音结束并发送
		handleTouchEnd(e){
			if (!this.connected){
				return;
			}
			this.recorderManager.stop();
			this.recorderManager.onStop(async (res) => {
				// console.log(res.tempFilePath)
				const file = await audioFile(res.tempFilePath)
				// console.log(file,'后台返回的文字');
				let lists = ['启动','暂停','减轻','加重','前进','后退','开频','关频','播放','关闭'];
				for(let i=0;i<lists.length;i++){
					let a = new RegExp(lists[i]);
					if(a.test(file)){
						// console.log(lists[i])
						this.getmsg(lists[i])
						return;
					}else{
						if(i==9){
							return this.$toast({
								title: '未识别有效语音'
							});
						}
					}
				}
			});
		},
		// aaa(){
		// 	const file = '减轻看'
		// 	let lists = ['启动','暂停','减轻','加重','前进','后退','开频','关频','播放','关闭'];
		// 	for(let i=0;i<lists.length;i++){
		// 		let a = new RegExp(lists[i]);
		// 		if(a.test(file)){
		// 			console.log(lists[i])
		// 			this.getmsg(lists[i])
		// 			return;
		// 		}else{
		// 			if(i==9){
		// 				return this.$toast({
		// 					title: '未识别有效语音'
		// 				});
		// 			}
		// 		}
		// 	}
		// },
		// 根据语音发送命令
		getmsg(value){
			if(value=='启动'){
				this.gosend('cmd{01}');
			}else if(value=='暂停'){
				this.gosend('cmd{02}');
			}else if(value=='减轻'){
				this.gosend('cmd{05}');
			}else if(value=='加重'){
				this.gosend('cmd{06}');
			}else if(value=='前进'){
				this.gosend('cmd{03}');
			}else if(value=='后退'){
				this.gosend('cmd{04}');
			}else if(value=='开频'){
				this.gosend('cmd{07}');
			}else if(value=='关频'){
				this.gosend('cmd{08}');
			}else if(value=='播放'){
				this.gosend('cmd{09}');
			}else if(value=='关闭'){
				this.gosend('cmd{10}');
			}
		},
		// 倒计时结束
		finish(){
			let that = this;
			console.log('服务已结束')
			that.gosend('cmd{15}');//清除蓝牙定时器
			that.$nextTick(() => {
				that.connected = false;
				uni.closeBLEConnection({
					deviceId: that.deviceId
				});
				that.stuName = '连接已断开';
				uni.showModal({
					content: '服务已结束',
					showCancel: false,
					confirmText: '确认',
					success: function (res) {
						if (res.confirm) {
							that.$Router.replaceAll({
								path: '/pages/user/user'
							});
						}
					}
				});
			});
		},
		// 重新连接
		newconnect(){
			let that = this;
			if(that.connected){
				that.connected = false;
				uni.closeBLEConnection({
					deviceId: that.deviceId
				});
			}
			that.$nextTick(() => {
				that.getinit();//二次连接
			});
		},
		// 初始化蓝牙
		getinit() {
			let that = this;
			uni.setNavigationBarTitle({
				title: '初始化蓝牙中...'
			});
			that.loading = true;
			uni.openBluetoothAdapter({
				success(res) {
					console.log('初始化蓝牙成功后搜索',res);
					//开始搜索附近蓝牙
					that.startBluetoothDevicesDiscovery();
				},
				fail: (err) => {
					that.$nextTick(() => {
						uni.showModal({
							content: '初始化失败，请打开手机蓝牙后重试',
							showCancel: false,
							confirmText: '我知道了',
							success: function (res) {
								if (res.confirm) {
									// that.$Router.replaceAll({
									// 	path: '/pages/user/user'
									// });
									that.loading = false;
								}
							}
						});
					});
					console.log('初始化蓝牙失败',err);
				}
			});
		},
		// 第二步 开始搜索附近的蓝牙设备
		startBluetoothDevicesDiscovery() {
			let that = this;
			uni.startBluetoothDevicesDiscovery({
				allowDuplicatesKey: true,
				interval: 100,
				success: (res) => {
					console.log('开始搜索附近的蓝牙设备', res);
					that.onBluetoothDeviceFound();
				}
			});
		},
		// 第三步 监听发现附近的蓝牙设备
		onBluetoothDeviceFound() {
			let that = this;
			uni.setNavigationBarTitle({
				title: '搜索蓝牙中...'
			});
			uni.showLoading({ title: '发现设备中...' });
			uni.onBluetoothDeviceFound((res) => {
				res.devices.forEach((device) => {
					if (!device.name && !device.localName) {
						return;
					}
					console.log('发现的蓝牙设备', device);
					// 第四步、 建立连接后停止搜索
					// if (device.localName == 'daocheng') {
					if (device.localName == that.jqrdevicename) {
						console.log('发现需要的蓝牙设备', device);
						that.deviceId = device.deviceId;
						uni.hideLoading();
						that.stopBluetoothDevicesDiscovery(1);
					}
					// console.log('蓝牙设备名称',device.name)
				});
			});
			setTimeout(function () {
				if (!that.deviceId) {
					uni.hideLoading();
					uni.showModal({
						content: '未检测到对应蓝牙设备，请返回重试',
						showCancel: false,
						confirmText: '我知道了',
						success: function (res) {
							if (res.confirm) {
								that.$Router.replaceAll({
									path: '/pages/user/user'
								});
							}
						}
					});
				}
			}, 60000);
		},
		// 第五步、 停止搜索
		stopBluetoothDevicesDiscovery(num) {
			let that = this;
			uni.stopBluetoothDevicesDiscovery({
				success: function (res) {
					if (num == 1) {
						that.$nextTick(() => {
							that.getbegin(that.deviceId, 1);
						});
					}
					console.log('停止搜索成功');
				},
				fail: function (res) {
					console.log('停止搜索失败');
				}
			});
		},
		// 启动蓝牙
		getbegin(deviceId, type) {
			let that = this;
			uni.setNavigationBarTitle({
				title: '正在连接'
			});
			that.readyRec = false;
			uni.createBLEConnection({
				deviceId,
				success: (res) => {
					that.connected = true;
					that.loading = false;
					uni.setNavigationBarTitle({
						title: '已连接'
					});
					// 若已知蓝牙设备的 deviceId、serviceId、以及读写特征值 直接调用
					// that.getNotify(deviceId, that.serviceId, that.characteristicId);
					// 读取BLE所有服务
					// that.getBLEDeviceServices(deviceId);
					uni.getBLEDeviceServices({
						deviceId: deviceId,
						success(res) {
							console.log(res,'获取的服务id')
							// 获取所有特征值
							uni.getBLEDeviceCharacteristics({
								deviceId: deviceId,
								serviceId:that.serviceId,
								success: (res) => {
									console.log(res,'所有特征值')
									console.log(res.characteristics[0].uuid,'当前特征值')
									// if(that.type==1){
									// 	startFw({id:that.id}).then(res => {
									// 		console.log('启动服务')
									// 	});
									// }
									// if(that.status==1){
									// 	that.beginTime = that.time;
									// 	let numbertime = Number(that.time);
									// 	if(numbertime<10){
									// 		numbertime = '0'+numbertime;
									// 	}
									// 	let strGoTime ='cmd{11,t='+numbertime+'m}';
									// 	that.gosend(strGoTime);//启动蓝牙定时器
									// 	that.$refs.uCountDown.start();//倒计时开始显示
										
									// 	that.status=2;
									// }
									// 若已知蓝牙设备的 deviceId、serviceId、以及读写特征值   可以直接启动 notify 功能监听蓝牙设备回传信息
									// // 开启通知（为了接收设备返回的信息）
									// uni.notifyBLECharacteristicValueChange({
									// 	deviceId,
									// 	serviceId:that.serviceId,
									// 	characteristicId:res.characteristics[0].uuid,
									// 	state: true,
									// 	success(res) {
									// 		console.warn('notifyBLECharacteristicValueChange success', res);
									// 		uni.setNavigationBarTitle({
									// 			title: '连接成功'
									// 		});
									// 		// that.showModalTips(that.rxdu + "\r开启通知成功")
									// 		that.readyRec = true;
									// 		// 接收设备推送过来的信息
									// 		uni.onBLECharacteristicValueChange(function(res){
									// 		    console.log("收到Notify",res);
									// 		    console.log("收到Notify数据",ab2hex(res.value));
									// 		})
									// 	},
									// 	fail: res => {
									// 		console.log('开启通知失败',res)
									// 	}
									// });
								},
								fail: res => {
									console.log('获取特征值失败',res)
								}
							})
						},
						fail(res) {
							console.log(res,'获取服务id失败')
						}
					})
					// 读取BLE所有特征值
					// that.getBLEDeviceCharacteristics(deviceId);
				},
				fail: (res) => {
					if (type == 1) {
						setTimeout(function () {
							that.getbegin(that.deviceId, 2);
						}, 2000);
					} else {
						that.loading = false;
						uni.showModal({
							// content: res.errMsg,
							content: '连接超时，' + res.errMsg,
							showCancel: false,
							confirmText: '我知道了',
							success: function (res) {
								if (res.confirm) {
									that.$Router.replaceAll({
										path: '/pages/user/user'
									});
								}
							}
						});
						console.log('连接设备失败', res);
					}
				}
			});
		},
		
		// 发送
		gosend(hex,stus) {
			console.log(hex, '要发送的数据');
			console.log('点击的启动stus=',stus);
			
			if (!this.connected)
				return this.$toast({
					title: '请先连接蓝牙设备...'
				});
			var that = this;
			if(stus == 1){//启动
				if(that.type==1){
					startFw({id:that.id}).then(res => {
						console.log('启动服务')
					});
					
					that.type='';//支付后只能启动一次服务
				}
				if(that.status==1){
					that.beginTime = that.time;
					let numbertime = Number(that.time);
					if(numbertime<10){
						numbertime = '0'+numbertime;
					}
					let strGoTime ='cmd{11,t='+numbertime+'m}';
					that.gosend(strGoTime);//启动蓝牙定时器
					that.$refs.uCountDown.start();//倒计时开始显示
					
					that.status=2;
				}
			}
			
			var buffer1;
			var strbuf = new Uint8Array(stringToBytes(hex)); //要发送的数据
			console.log('strtobyte ', strbuf);
			buffer1 = strbuf.buffer;
			console.log('Txbuf = ', buffer1);
			if (buffer1 == null) return;

			console.log('============================>');
			console.log(that.deviceId);
			console.log(that.serviceId);
			console.log(that.characteristicId);
			console.log(buffer1);

			uni.writeBLECharacteristicValue({
				deviceId: that.deviceId,
				serviceId: that.serviceId,
				characteristicId: that.characteristicId,
				value: buffer1,
				success: function (res) {
					// success
					console.log('success  指令发送成功');
					console.log(res);
				},
				fail: function (res) {
					uni.showModal({
						content: '检查服务是否结束',
						showCancel: false,
						confirmText: '我知道了'
					});
					// fail
					console.log(res);
				},
				complete: function (res) {
					// complete
				}
			});
		}
	},
	onHide() {
		let that = this;
		// 关闭蓝牙
		if (that.connected) {
			console.log('关闭蓝牙');
			// uni.setStorageSync('jqrdevicename', '');
			// that.gosend('cmd{15}');//清除蓝牙定时器
			that.connected = false;
			uni.closeBLEConnection({
				deviceId: that.deviceId
			});
		}
		// 如果没有搜索到蓝牙,停止搜索
		if (!that.deviceId) {
			that.stopBluetoothDevicesDiscovery();
		}
	},
	onUnload() {
		let that = this;
		// 关闭蓝牙
		if (that.connected) {
			console.log('关闭蓝牙');
			// uni.setStorageSync('jqrdevicename', '');
			// that.gosend('cmd{15}');//清除蓝牙定时器
			that.connected = false;
			uni.closeBLEConnection({
				deviceId: that.deviceId
			});
		}
		// 如果没有搜索到蓝牙,停止搜索
		if (!that.deviceId) {
			that.stopBluetoothDevicesDiscovery();
		}
	}
};
</script>

<style lang="scss" scoped>
.tops {
	width: 300rpx;
	height: 120rpx;
}
.operate{
	text-align: center;
	
	.m-t-20{
		font-size: 22rpx;
		background: #003fde;
		color: #fff;
		padding: 15rpx;
		border-radius: 10rpx;
		width: 190rpx;
	}
}
.boxes {
	border-radius: 30rpx;
	color: #000;
	font-size: 28rpx;
	padding: 30rpx;
	padding-top: 0;
	.m-t-40 {
		view {
			font-weight: bold;
			font-size: 75rpx;
			text-align: center;
			padding: 30rpx 85rpx;
			border: 1px solid #999;
			border-radius: 20rpx;
		}
	}
}
.base {
	color: #003fde;
	font-size: 50rpx;
	text-align: center;
	font-weight: bold;
	margin: 30rpx;
	padding: 0rpx 30rpx;
	border: 1px solid #999;
	border-radius: 20rpx;
}
</style>
